package com.sws.weixin.button;

import com.sws.weixin.token.TokenUtil;
import com.sws.weixin.util.HttpUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 微信菜单按钮创建工具
 */
@Component
public class TestButton {
    
    @Value("${wx.appid}")
    private String appId;
    
    @Value("${redirect.domain}")
    private String redirectDomain;
    
    @Autowired
    private TokenUtil tokenUtil;
    
    /**
     * 创建微信公众号菜单
     * @return 创建结果
     */
    public String createMenu() {
        System.out.println("开始创建菜单...");
        System.out.println("使用配置: appId=" + appId + ", redirectDomain=" + redirectDomain);

        //创建一级菜单
        Button button = new Button();
        List<AbstractButton> buttons = new ArrayList<>();
        //一级菜单中的第一个按钮 - 工作人员认证
        // 构建微信网页授权URL，用于获取工作人员信息并跳转到认证页面
        String staffAuthRedirectUrl;
        try {
            // 清理域名中可能存在的路径部分
            String cleanDomain = redirectDomain;
            if (cleanDomain.contains("/")) {
                cleanDomain = cleanDomain.split("/")[0];
            }
        
            // 正确编码重定向URL
            staffAuthRedirectUrl = URLEncoder.encode("http://" + cleanDomain + "/wx/getStaffAuthUserInfo", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            System.err.println("URL编码失败: " + e.getMessage());
            staffAuthRedirectUrl = "http://" + redirectDomain + "/wx/getStaffAuthUserInfo";
        }
        
        String staffAuthUrl = String.format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s#wechat_redirect",
                appId,
                staffAuthRedirectUrl,
                "snsapi_userinfo");
                
        System.out.println("生成的工作人员认证URL: " + staffAuthUrl);
        
        ViewButton staffAuthButton = new ViewButton("员工认证", staffAuthUrl);
        
        //一级菜单中的第二个按钮 - 修改为用户认证页面
        // 构建微信网页授权URL，用于获取用户信息并跳转到注册页面
        //先引导用户访问地址进行授权，之后改用模版消息来封装
        String redirectUrl;
        try {
            // 清理域名中可能存在的路径部分
            String cleanDomain = redirectDomain;
            if (cleanDomain.contains("/")) {
                cleanDomain = cleanDomain.split("/")[0];
            }
        
            // 正确编码重定向URL
            redirectUrl = URLEncoder.encode("http://" + cleanDomain + "/wx/getSignUpUserInfo", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            System.err.println("URL编码失败: " + e.getMessage());
            redirectUrl = "http://" + redirectDomain + "/wx/getSignUpUserInfo";
        }
        
        String authUrl = String.format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s#wechat_redirect",
                appId,
                redirectUrl,
                "snsapi_userinfo");
        
        System.out.println("生成的授权URL: " + authUrl);
        
        ViewButton viewButton = new ViewButton("顾客认证", authUrl);
        
        //一级菜单中的第三个按钮（二级菜单）
        SubButton subButton = new SubButton("更多菜单");
        List<AbstractButton> subButtons = new ArrayList<>();
        
        // 添加技师顾客管理菜单
        String staffManageUrl;
        try {
            String cleanDomain = redirectDomain;
            if (cleanDomain.contains("/")) {
                cleanDomain = cleanDomain.split("/")[0];
            }
            staffManageUrl = URLEncoder.encode("http://" + cleanDomain + "/wx/getStaffManage", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            System.err.println("URL编码失败: " + e.getMessage());
            staffManageUrl = "http://" + redirectDomain + "/wx/getStaffManage";
        }
        
        String staffManageAuthUrl = String.format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s#wechat_redirect",
                appId,
                staffManageUrl,
                "snsapi_userinfo");
        
        System.out.println("生成的技师顾客管理URL: " + staffManageAuthUrl);
        ViewButton staffManageButton = new ViewButton("技师：顾客管理", staffManageAuthUrl);
        
        // 添加顾客预约管理菜单
        String customerReservationUrl;
        try {
            String cleanDomain = redirectDomain;
            if (cleanDomain.contains("/")) {
                cleanDomain = cleanDomain.split("/")[0];
            }
            customerReservationUrl = URLEncoder.encode("http://" + cleanDomain + "/wx/getCustomerReservation", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            System.err.println("URL编码失败: " + e.getMessage());
            customerReservationUrl = "http://" + redirectDomain + "/wx/getCustomerReservation";
        }
        
        String customerReservationAuthUrl = String.format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s#wechat_redirect",
                appId,
                customerReservationUrl,
                "snsapi_userinfo");
        
        System.out.println("生成的顾客预约管理URL: " + customerReservationAuthUrl);
        ViewButton customerReservationButton = new ViewButton("顾客：预约管理", customerReservationAuthUrl);
        
        // 添加二级菜单按钮
        subButtons.add(staffManageButton);
        subButtons.add(customerReservationButton);
        //二级菜单的第三个按钮
        subButtons.add(new ViewButton("千锋","http://www.qfedu.cn"));
        subButton.setSub_button(subButtons);
        
        //把一级菜单中的三个按钮添加进集合
        buttons.add(staffAuthButton);
        buttons.add(viewButton);
        buttons.add(subButton);
        //把集合添加到一级菜单中
        button.setButton(buttons);
        //转换成json字符串
        JSONObject jsonObject = JSONObject.fromObject(button);
        String json = jsonObject.toString();
        String url = String.format("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=%s", tokenUtil.getAccessToken());
        //发送请求
        String result = HttpUtil.doPostByButton(url, json);
        System.out.println(result);
        
        return result;
    }
}
